/**
 * Copyright 2006 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.ocean.main.analyzer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;

import org.apache.lucene.analysis.StopAnalyzer;
import org.apache.lucene.analysis.StopFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.ocean.main.util.FileLoader;
import org.apache.ocean.main.util.XMLUtil;
import org.jdom.Element;

/**
 */
public class StopFilterFactory extends BaseTokenFilterFactory {
	public static Logger log = Logger.getLogger(StopFilterFactory.class.getName());
	private Set stopWords = StopFilter.makeStopSet(StopAnalyzer.ENGLISH_STOP_WORDS);
	private String filePath;
	private boolean ignoreCase;

	public void init(Element initElement, FileLoader fileLoader) throws Exception {
		super.init(initElement, fileLoader);
		filePath = XMLUtil.getAttributeString("file", initElement);
		ignoreCase = getBoolean("ignoreCase", false);
		String stopListString = fileLoader.getString(filePath);
		List<String> wlist = getLines(stopListString);
		stopWords = StopFilter.makeStopSet((String[])wlist.toArray(new String[0]), ignoreCase);
	}

	public static List<String> getLines(String string) throws IOException {
		BufferedReader input = new BufferedReader(new StringReader(string));
		ArrayList<String> lines = new ArrayList<String>();
		for (String word = null; (word = input.readLine()) != null;) {
			// skip comments
			if (word.startsWith("#")) {
				continue;
			}
			word = word.trim();
			// skip blank lines
			if (word.length() == 0) {
				continue;
			}
			lines.add(word);
		}
		return lines;
	}

	public Set createStopWordsSet(String[] array) {
		return StopFilter.makeStopSet(array, ignoreCase);
	}

	public TokenStream create(TokenStream input) {
		return new StopFilter(input, stopWords, ignoreCase);
	}
}
